package api

import (
	"gino/app/common"
	"gino/app/constant"
	"gino/app/model"
	"gino/app/service"
	"gino/pkg/glog"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
)

var User = new(userApi)

type userApi struct{}

func (a *userApi) Register(c *gin.Context) {

	var req model.UserRegisterReq
	if err := c.BindJSON(&req); err != nil {
		common.Fail(c, 0, "error", nil)
		return
	}

	err := service.User.Register(c.Request.Context(), req)
	if err != nil {
		glog.Errorf("[api/v1/user]Register service.User.Register Err：%v", err)
		common.Fail(c, 0, err.Error(), nil)
		return
	}

	common.Success(c, "success", nil)
}

func (a *userApi) Login(c *gin.Context) {

	var req model.UserLoginReq
	if err := c.BindJSON(&req); err != nil {
		common.Fail(c, 0, "error", nil)
		return
	}

	ret, err := service.User.Login(c.Request.Context(), req)
	if err != nil {
		common.Fail(c, 0, err.Error(), nil)
		return
	}

	common.Success(c, "success", ret)
}

func (a *userApi) List(c *gin.Context) {

	params := model.UserListReq{
		PageInfo: common.PageInfo{
			Page:     cast.ToInt(c.DefaultQuery("page", "1")),
			PageSize: cast.ToInt(c.DefaultQuery("page_size", string(constant.PageSize))),
		},
	}

	ret, err := service.User.List(c.Request.Context(), params)
	if err != nil {
		return
	}

	common.Success(c, "success", ret)
}
